package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: Geekvin
 * @CreateTime: 2022-10-15 22:34
 * @Version:v1.0.0
 * @Description:
 */
@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String fileServerUrl;

    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception {
        //1、加载配置文件
        String configFile = this.getClass().getClassLoader().getResource("tracker.conf").getFile();
        String path = "";
        //2、初始化
        if (configFile != null) {
            ClientGlobal.init(configFile);
            //3、创建trackerClient
            TrackerClient trackerClient = new TrackerClient();
            //4、创建trackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //5、创建storageClient1
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
            //6、上传文件
            //获取文件后缀名
            String extName = FilenameUtils.getExtension(file.getOriginalFilename());
            path = storageClient1.upload_file1(file.getBytes(), extName, null);
            System.out.println("文件上传路径为：" + fileServerUrl + path);
        }

        return Result.ok(fileServerUrl + path);
    }


}
